/**
 * Created by Administrator on 2015/1/24.
 */


var Config = require('./config').Config();
var logger = require('./logger');
var utils = require('./utils');

var command = require('./command');
require('./ghost-command');

exports.verify = function (query) {
    var signature = query['signature'];
    var timestamp = query['timestamp'];
    var nonce = query['nonce'];
    var sha1Content = calcSig(Config.token, timestamp, nonce);
    if (signature == sha1Content) {
        return true;
    }
    else {
        return false;
    }
}

exports.process = function (xmlParam) {
    var jsonParam = utils.paraseXML(xmlParam);
    logger.debug("jsonParam", jsonParam);
    var message = this.receive(jsonParam);
    var result = this.reply(jsonParam, message);
    return result;
}

exports.receive = function (jsonParam) {
    var check = msgTypeCheck(jsonParam['MsgType']);
    if (0 == check) {
        var reuslt = command.execute(jsonParam);
        console.log(reuslt)
        return reuslt;
    } else {
        return check;
    }
    return "";
}


exports.reply = function (jsonParam, message) {
    var replyTo = jsonParam['FromUserName'];
    var jsonResult = {
        toUser: replyTo,
        fromUser: Config.weixinUser,
        time: new Date().getTime(),
        content: message
    }
    logger.debug("jsonResult", jsonResult);
    var xmlResult = utils.processEjsTemplate(Config.replyText, jsonResult);
    logger.debug("xmlResult", xmlResult);
    return xmlResult;
}


var msgTypeCheck = function (type) {
    if ("text" == type) {
        return 0;
    } else {
        return "仅支持文本消息";
    }
}

var crypto = require('crypto');

//根据微信规则计算signature
function calcSig(token, timestamp, nonce) {
    var s = [token, timestamp, nonce].sort().join('')
    return crypto.createHash('sha1').update(s).digest('hex')
}